<?php

class PagamentoController extends Site_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        
    }

    public function carrinhoAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/pagamento.js');
        
        Zend_Loader::loadClass('tools','library');
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = '0';
        if(isset($sessao->carrinho)) $cursos .= @implode(',', $sessao->carrinho);
        
        
        $obj = new Ead_Model_DbTable_Curso();
        $row = $obj->fetchAll('CUR_ID in (' . $cursos . ')');
        $this->view->row = $row;
    }

    public function pagamentoAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/pagamento.js?1=1');
        
        Zend_Loader::loadClass('tools','library');
        
        $this->verificaLogin();
        
        $this->verificaCarinho();
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = implode(',', $sessao->carrinho);
        
        $obj = new Ead_Model_DbTable_Curso();
        $row = $obj->fetchAll('CUR_ID in (' . $cursos . ')');
        
        $this->view->row = $row;
       
    }
    
    public function referencia(){
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        
        $usu_id = $s_user->read()->USU_ID;
        
        $dathor = date('Y-m-d H:i:00');

        $referencia = md5($usu_id . $dathor);

        return $referencia;
    }


    public function retornoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();    
        
        $cont = 0;
        if ($this->getRequest()->isPost()) {
            $cont = 1;
            $referencia = $this->_getParam('Referencia', 0);

            $find = 'COM_REF = ' . $referencia;

            $obj = new Ead_Model_DbTable_Compra();
            $result = $obj->fetchAll($find);
            foreach ($result as $res) {
                $data = array(
                    'COM_TRANID' => $this->_getParam('TransacaoID'),
                    'COM_STATRA' => $this->_getParam('StatusTransacao'),
                    'COM_TPOPAGSEG' => $this->_getParam('TipoPagamento'),
                    'COM_INT' => $res->COM_INTERACOES + 1,
                );

                $obj = new Ead_Model_DbTable_Compra();

                $obj->update($data, 'COM_ID = ' . $res->COM_ID);
            }
            // teste depois tirar
            if($cont == 0){
                $data = array(
                    'COM_INT' => 1,
                );
                
                $obj = new Ead_Model_DbTable_Compra();

                $obj->update($data, 'COM_TPOPAG = "p"');
            }
        }
    }
    
    
    
    
    
    public function retiraprocarrinhoAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();         
        
        $ok = false;
        
        $cur_id = $this->_getParam('id', 0);

        $sessao = new Zend_Session_Namespace('Carrinho');
        //$sessao->carrinho = array($cur_id);
        
        $arr = $sessao->carrinho; 
        
        if(array_search($cur_id, $arr) !== FALSE) {
            $ok = true;
            $chave = array_search($cur_id, $arr);
            unset($arr[$chave]); 
            if(array_search($cur_id, $arr) !== FALSE) {
                $ok = true;
                $chave = array_search($cur_id, $arr);
                unset($arr[$chave]); 
            }
        }
        
        $sessao->carrinho = $arr;
        
        
        echo json_encode(array('ok' => $ok));
        
    }
    
    public function finalizarAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $html = '';
        $dialog = '';
        $pagina = '';
        $msg = '';
        $ok = TRUE;
        
        if($this->getRequest()->isPost() == false) return FALSE;
        
        $op_pag = $this->_getParam('op_pag',0);
        $op_chq_vez = $this->_getParam('op_chq_vez',0);
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        
        $usu_id = $s_user->read()->USU_ID;
        
        $referencia = $this->referencia(); 
        
        $dathor = date('Y-m-d H:i:00');
        
        $arr = array('usu_id'=>$usu_id,'referencia'=>$referencia,'dathor'=>$dathor,'tpopag'=>$op_pag,'vezes'=>$op_chq_vez,'pag_sta'=>'');
        
        if($op_pag == 'P') $html = $this->for_pagseguro($arr);
        else if($op_pag == 'C'){
            
            if($op_chq_vez <= 0){
                $ok = FALSE;
                $msg = 'Escolha a quantidade de vezes de pagamento!';
            }else
            {
                $dialog = $this->view->partial('pagamento/dadoscq.phtml', array());
                $dialog .= '<script>$(function(){  
                    $( "#dialog" ).dialog("option","title","Pagamento com cheque." );
                    $("#dialog").dialog("open"); });</script>';
                $pagina = 'impcq';
                
                $this->registraCompra($arr);
            }
        }
        else if($op_pag == 'D'){
            $dialog = $this->view->partial('pagamento/dadosdp.phtml', array());
            $dialog .= '<script>$(function(){  
                $( "#dialog" ).dialog("option","title","Pagamento com depósito." );
                $("#dialog").dialog("open"); });</script>';
            $pagina = 'impdp';
            
            $this->registraCompra($arr);
        }
        else if($op_pag == 'G'){
       
            $dialog = '<script> window.location.href = URLBASE+"/"+CONTROL+"/finalizado"; </script>';
            
            $arr['pag_sta'] = 'Completo';
            
            $this->registraCompra($arr);
        }
        else{
            $ok = FALSE;
            $msg = 'Escolha uma opção de pagamento!';
        }
        
        if($ok == TRUE){
            $sessao = new Zend_Session_Namespace('Carrinho');
            $sessao->carrinho = '';
        }
        
        echo json_encode(array('ok' => $ok, 'html' => $html, 'dialog' => $dialog, 'pagina'=>$pagina,'msg'=>$msg,'redirect' => false));
    }
    
    public function for_pagseguro($arr) {
        // token DDBD325656434617A5C376E8755C14A3
        
        $dados = array();
        
        $op_pag = $arr['tpopag'];
        
        $referencia = $arr['referencia']; 
        
        $usu_id = $arr['usu_id'];
        
        $dathor = $arr['dathor'];
        
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = implode(',', $sessao->carrinho);
        $obj = new Ead_Model_DbTable_Curso();
        $rows = $obj->fetchAll('CUR_ID in (' . $cursos . ')');
        foreach($rows as $key => $r) {
            
            $hoje = strtotime(date('Y-m-d'));
            $datapro = strtotime($r->CUR_PROMDAT);
            $valor = $r->CUR_VLR;
            if($datapro >= $hoje){
                $valor = $r->CUR_PROM;
            }
            
            $dados[$key] = array(
                    'itemId' => $r->CUR_ID,
                    'itemDescription' => $r->CUR_NOM,
                    'itemAmount' => $valor,
                    'itemQuantity' => 1,
                );
            
        }
        
        $this->registraCompra(array('usu_id'=>$usu_id,'referencia'=>$referencia,'dathor'=>$dathor,'tpopag'=>$op_pag,'vezes'=>''));
            
        $find = 'USU_ID = ' . $usu_id;
        $obj = new Ead_Model_DbTable_Usuarios();
        $result = $obj->fetchAll($find);
        foreach ($result as $res) {
            $senderName = $res->USU_NOME;
            $senderEmail = $res->USU_EMAIL;
        }
        
        
        $html = '
            <form id="form_pagamento" method="post" action="https://pagseguro.uol.com.br/v2/checkout/payment.html">  
               <input type="hidden" name="receiverEmail" value="alenkar.k@gmail.com">
               <input type="hidden" name="currency" value="BRL">
               ';
       
        $count = 0; 
        foreach ($dados as $dado) { 
            $count += 1;
            $html .= '
                <input type="hidden" name="itemId'.$count.'" value="'.$dado['itemId'].'">  
                <input type="hidden" name="itemDescription'.$count.'" value="'.$dado['itemDescription'].'">  
                <input type="hidden" name="itemAmount'.$count.'" value="'.$dado['itemAmount'].'">  
                <input type="hidden" name="itemQuantity'.$count.'" value="'.$dado['itemQuantity'].'">  
                <input type="hidden" name="itemWeight'.$count.'" value="0">  
            ';
        }

        $html .= '
                <input type="hidden" name="reference" value="'.$referencia.'">  

                <input type="hidden" name="senderName" value="'.$senderName.'">  
                <input type="hidden" name="senderAreaCode" value="0">  
                <input type="hidden" name="senderPhone" value="00000">  
                <input type="hidden" name="senderEmail" value="'.$senderEmail.'">  
                    
            </form>
            <script>document.getElementById("form_pagamento").submit();</script>
         ';
            
        return $html;
    }
    
    public function  registraCompra(array $arr){
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = implode(',', $sessao->carrinho);
        $obj = new Ead_Model_DbTable_Curso();
        $rows = $obj->fetchAll('CUR_ID in (' . $cursos . ')');
        $this->verificaPossuiCurso($rows->toArray());
        $arr_com = array();
        foreach($rows as $key => $r) {
            
            if($arr['tpopag'] == 'D'){
                $valor = $r->CUR_VLR - (($r->CUR_VLR * $r->CUR_POR) / 100);
            }else{
                $valor = $r->CUR_VLR;
            }
            
            $hoje = strtotime(date('Y-m-d'));
            $datapro = strtotime($r->CUR_PROMDAT);
            $valor = $r->CUR_VLR;
            if($datapro >= $hoje){
                $valor = $r->CUR_PROM;
            }
            
            $data = array(
                'CUR_ID'        => $r->CUR_ID,
                'USU_ID'        => $arr['usu_id'],
                'COM_REF'       => $arr['referencia'],
                'COM_DATHOR'    => $arr['dathor'],
                'COM_VLR'       => $valor,
                'COM_TPOPAG'    => $arr['tpopag'],
                'COM_STATRA'    => 'Aguardando Pagto',
                'COM_VES'       => $arr['vezes'],
                'COM_DES'       => $r->CUR_POR,
                'COM_DATPAG'    => date('Y-m-d')
            );
            
            if(strlen($arr['pag_sta']) > 0){
                $data['COM_STATRA'] = $arr['pag_sta'];
            }
            
            $obj = new Ead_Model_DbTable_Compra();

            $obj->insert($data);
            $arr_com[$key] =  $obj->getAdapter()->lastInsertId(); 
        }
        
        Zend_Loader::loadClass('envioemail','library');
        envioemail::CompraFinalizada($arr_com,$arr);
        
        return true;
        
    }

    public function impcqAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setRender('dadoscq');
        echo '<script>window.print();</script>';
    }
    
    public function impdpAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setRender('dadosdp');
        echo '<script>window.print();</script>';
    }
    
    public function finalizadoAction() {
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $sessao->carrinho = '';
    }
    public function meuscursosAction() {
        $sessao = new Zend_Session_Namespace('Carrinho');
        $sessao->carrinho = '';
    }
    
    public function buscaoppagAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $html = '';
        $ok = TRUE;
        
        $op_pag = $this->_getParam('op_pag',0);
        
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = implode(',', $sessao->carrinho);
   
        $obj = new Ead_Model_DbTable_Curso();
        $rows = $obj->fetchAll('CUR_ID in (' . $cursos . ')');
        
        foreach($rows as $row) { 
            
            if($op_pag == "C" && $row['CUR_VES'] >  0 ){
                $html = 'Vezes: '; 
                for($i=1; $i <= $row['CUR_VES'];$i++)
                {
                    $html .= '<label><input type="radio" name="chq_vez" value="'.$i.'" class="chq_vez" /> '.$i.' x</label>';
                }
            }
            else if($op_pag == 'D'){
                $html = 'Porcentagem de desconto: <strong>'.$row['CUR_POR'].'%</strong>';
            }
        }
        
        echo json_encode(array('ok' => $ok, 'html' => $html));
    }
    
    public function verificaCarinho(){
        $sessao = new Zend_Session_Namespace('Carrinho');
        $cursos = implode(',', $sessao->carrinho);
        if(strlen($cursos) <= 0 || $cursos <= '0'){
          $this->_helper->redirector('carrinho', 'pagamento', array());
        }  
    }
    
    public function verificaPossuiCurso($cursos){
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $USU_ID = $s_user->read()->USU_ID;
        
        foreach($cursos as $key => $r) {
            
            //$where = 'CUR_ID = '. $r['CUR_ID'].' AND USU_ID = '. $USU_ID.' AND COM_STATRA like "Completo"';
            //$obj = new Ead_Model_DbTable_Compra();
            //$result = $obj->fetchAll($where);
            
            $hoje = date('Y-m-d');
            $where = 'COMPRA.CUR_ID = '. $r['CUR_ID'].' AND COMPRA.USU_ID = '. $USU_ID.' AND COMPRA.COM_STATRA like "Completo"';
            $obj = new Ead_Model_DbTable_Compra();
            
            $sql = $obj->select()->setIntegrityCheck(false);
            $sql->from('COMPRA')
                ->join('CURSO','CURSO.CUR_ID = COMPRA.CUR_ID AND ( DATEDIFF("'.$hoje.'",COMPRA.COM_DATPAG) <= CURSO.CUR_QTDDIAACE AND DATEDIFF("'.$hoje.'",COMPRA.COM_DATPAG) >= 0 ) ') 
                ->where($where)->order('COMPRA.COM_DATHOR DESC');

            $result = $obj->fetchAll($sql);
            foreach($result as $res){
                //$this->_helper->redirector('meuscursos');
            
                $script = '<script>location.href = "'.$this->_urlbase.'/pagamento/meuscursos";</script>';
                echo json_encode(array('ok' => true, 'html' => $html, 'dialog' => $script, 'pagina'=>'','msg'=>'','redirect' => true));
                exit();
            }
        }
    }  
}

